<template>
  <div class="editInfo">
    <hmNavbar
      :title="title"
      @back="back"
      @save="save"
      :hasSave="value !== user[prop]"
    ></hmNavbar>
    <div class="ipt" v-if="prop !== 'avatar'">
      <van-field v-model="value"> </van-field>
    </div>
    <div class="avatarbox" v-else>
      <van-uploader
        :before-read="beforeRead"
        :after-read="afterRead"
        v-model="fileList"
        :max-count="1"
      />
    </div>
  </div>
</template>

<script>
// 导入辅助函数快速取出store的数据
import { mapState, mapActions } from 'vuex'
// 导入修改请求
import { editUser, upload } from '@/api/login.js'

export default {
  name: 'edit',
  data () {
    return {
      title: '', // 动态标题
      value: '', // 输入框绑定数据
      prop: '', // route.query的值,
      fileList: [] // 是图片上传需要的存储在数组中
    }
  },
  computed: {
    ...mapState(['user'])
  },

  created () {
    this.prop = this.$route.query.prop
    this.value = this.user[this.prop]
    if (this.prop === 'nickname') {
      this.title = '修改昵称'
    } else if (this.prop === 'intro') {
      this.title = '修改个人简介'
    } else if (this.prop === 'position') {
      this.title = '修改岗位'
    } else if (this.prop === 'avatar') {
      this.title = '修改头像'
      this.fileList.push({
        url: process.env.VUE_APP_BaseURL + this.user.avatar
      })
    }
  },
  methods: {
    ...mapActions(['setUserInfo']),
    // 选择图片的过程就要判断检验
    beforeRead (file) {
      // 检验图片类型
      const imgType = file.type === 'image/jpeg' || file.type === 'image/png'
      const imgSize = file.size / 1024 / 1024 < 2
      if (!imgType) {
        this.$toast.fail('图片类型只支持jpeg/png格式')
      }
      if (!imgSize) {
        this.$toast.fail('图片大小不超过2MB')
      }
      return imgType && imgSize
    },
    // 图片选择完毕后的回调
    async afterRead (file) {
      console.log('file', file.file)
      const res = await upload(file.file)
      console.log('res', res)
      this.value = res.data[0].id
    },
    back () {
      this.$router.back()
    },
    async save () {
      // 提示用户
      this.$toast({
        type: 'loading',
        message: '加载中',
        duration: 0
      })
      // 发起请求 但不写死
      await editUser({
        [this.prop]: this.value
      })
      this.setUserInfo()
      this.$router.back()
      this.$toast.clear()
    }
  }
}
</script>

<style lang="less" scoped>
.editInfo {
  .ipt {
    padding: 15px 20px;
    /deep/ .van-cell.van-field {
      background-color: rgb(243, 243, 243);
      border-radius: 6px;
    }
  }
  .avatarbox {
    text-align: center;
    /deep/ .van-image.van-uploader__preview-image,
    /deep/ .van-uploader__upload {
      width: 200px;
      height: 200px;
    }
  }
}
</style>
